package factory

import (
	"dingusxp/trial/guestbook/store"
	"fmt"
	"sync"
)

var (
	providersMu sync.RWMutex
	providers   = make(map[string]store.Store)
)

func Register(name string, store store.Store) {
	providersMu.Lock()
	defer providersMu.Unlock()

	if store == nil {
		panic("invalid store for " + name + ": is null")
	}

	if _, dup := providers[name]; dup {
		panic("store for " + name + " has been registerred before")
	}

	providers[name] = store
}

func New(name string) (store.Store, error) {
	providersMu.RLock()
	store, ok := providers[name]
	providersMu.RUnlock()

	if !ok {
		return nil, fmt.Errorf("store for %s does not exists!", name)
	}

	return store, nil
}
